<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Db;


class LeapController extends Controller
{
    protected function initialize(){
	 	parent::initialize();
		header('Access-Control-Allow-Origin:*');
    }
    public function index(){
       
        
        return $this->fetch();
    }
    
    public function pay(){
        $param = input('param.');
        $orderNo = getSN('IN_');
        $amount = (int)$param['price'];
        $data['mch_id']  = config("app.leappay.mchId");
        $data['order_sn'] = $orderNo;
        $data['money'] = $amount;
        $data['goods_desc'] = "TEST";
        $data['client_ip'] = getIP();
        $data['format'] = "page";
        $data['notify_url'] = getHttpType().$_SERVER['HTTP_HOST']."/api/leap/notify";
        $data['time'] = time();
        
        $sign = $this->getSign($data);
        ksort($data);
        $data['sign'] = $sign;
        
        $posturl = config('app.leappay.rechargeNewUrl');
         $res = Db::name('user_recharge')->insert([
                'uid'           => $param['uid'],
                'order_number'  => $orderNo,
                'type'          => $param['typeid'],
                'bid'           => $param['bid'],
                'money'         => $amount,
                'state'         => 3,
                'add_time'   => time(),
                'postscript'  => $param['name'],
                'bank_code'  => 'Leap'
    
            ]); 
        $response = $this->send_post($posturl,$data);
    
       return $response;
    }
    
    private function getSign($data){
        ksort($data);
        $secretKey = config('app.leappay.secretKey');
        $str='';
        foreach($data as $k=>$v){
            if($v){
                $str.= $k."=".$v."&";
            }
        }
        $sign = md5($str."key=".$secretKey);
        return $sign;
    }
    
    public function send_post($url,$post){
    $ch = curl_init();	
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;

}
    public function notify(){
        $param = input('param.');
        
        $file = file_put_contents('./leap_notify.log',json_encode($param)."\r\n",FILE_APPEND);
        
        $sign = $param['sign'];
        unset($param['sign']);
        $order = Db::name('user_recharge')->where('order_number',$param['sh_order'])->find();
        $uid = $order['uid'];
        $notifySign = $this->getSign($param);

        // 未完成的订单
        if($notifySign == $sign){
            //0已提交 1已接单 2超时补单 3订单失败 4交易完成 5未接单
            switch($param['state']){
                case "0":
                case "1":
                    Db::name('user_recharge')->where('order_number',$param['sh_order'])->update(['remarks'=>$param['pt_order']]);
                break;
                case "2":
                case "4":
                    if($order['state'] !=1){
                        Db::name('user_recharge')->where('order_number',$param['sh_order'])->where('state',3)->update(['daozhang_money'=>$param['money'],'dispose_time'=>time(),'state'=>1]);
                        Db::name('user_total')->where('uid' ,$uid)->setInc('balance', $param['money'])->setInc('total_recharge',$param['money'])->setInc('total_balance',$param['money']);
                    }
                break;
                case "3":
                case "5":
                    Db::name('user_recharge')->where('order_number',$param['sh_order'])->update(['state'=>2]);
                break;
				default:
					$file = file_put_contents('./leap_notify.log',"状态码未找到".$param['state']."\r\n",FILE_APPEND);
                
            }
        }else{
            $file = file_put_contents('./leap_notify.log',"签名失败"."\r\n",FILE_APPEND);
        }
        
        die('success');exit;
    }



    /**
     * 提现回调
     */
    public function out_notify(){
        $param = input('param.');

        $file = file_put_contents('./transaction_notify.log',json_encode($param)."\r\n",FILE_APPEND);

        $sign = $param['sign'];
        unset($param['sign']);
        $order = Db::name('user_withdrawals')->where('order_number',$param['sh_order'])->find();
        $uid = $order['uid'];
        $notifySign = $this->getSign($param);

        // 未完成的订单
        if($notifySign == $sign){
            //0已提交 1已接单 2超时补单 3订单失败 4交易完成 5未接单
            switch($param['state']){
                case "0":
                case "1":
                    Db::name('user_recharge')->where('order_number',$param['sh_order'])->update(['remarks'=>$param['pt_order']]);
                    break;
                case "2":
                case "4":
                    if($order['state'] !=1){
                        Db::name('user_withdrawals')->where('order_number',$param['sh_order'])->where('state',3)->update(['fee'=>$param['money'],'set_time'=>time(),'state'=>1]);
//                        Db::name('user_total')->where('uid' ,$uid)->setInc('balance', $param['money'])->setInc('total_recharge',$param['money'])->setInc('total_balance',$param['money']);
                    }
                    break;
                case "3":
                case "5":
                    Db::name('user_withdrawals')->where('order_number',$param['sh_order'])->update(['state'=>2]);
                    break;
                default:
                    $file = file_put_contents('./trans_notify.log',"状态码未找到".$param['state']."\r\n",FILE_APPEND);

            }
        }else{
            $file = file_put_contents('./trans_notify.log',"签名失败"."\r\n",FILE_APPEND);
        }

        die('success');exit;
    }




        
   

}